package logic

import (
	"context"
	"encoding/json"
	"net/http"
	"zg4_month_exam/user/common"

	"zg4_month_exam/user/rpc/internal/svc"
	"zg4_month_exam/user/rpc/pb/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type SearchLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSearchLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchLogic {
	return &SearchLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SearchLogic) Search(in *user.SearchRequest) (*user.Response, error) {
	// todo: add your logic here and delete this line
	switch in.Choose {
	case 1:
		data, err := common.EsSearch(in.Index, in.Search, int(in.Page))
		if err != nil {
			return &user.Response{
				Code: -1,
				Msg:  "失败",
				Data: nil,
			}, nil
		}
		s, _ := json.Marshal(data)
		return &user.Response{
			Code: http.StatusOK,
			Msg:  "成功",
			Data: s,
		}, nil
	case 2:
		data, err := common.Sort(in.Index)
		if err != nil {
			return &user.Response{
				Code: -1,
				Msg:  "失败",
				Data: nil,
			}, nil
		}
		s, _ := json.Marshal(data)
		return &user.Response{
			Code: http.StatusOK,
			Msg:  "成功",
			Data: s,
		}, nil
	case 3:
		data, err := common.SortSearch(in.Index, in.Search)
		if err != nil {
			return &user.Response{
				Code: -1,
				Msg:  "失败",
				Data: nil,
			}, nil
		}
		s, _ := json.Marshal(data)
		return &user.Response{
			Code: http.StatusOK,
			Msg:  "成功",
			Data: s,
		}, nil
	case 4:
		//根据索引统计数据
		data := common.CountData(in.Index)
		s, _ := json.Marshal(data)
		return &user.Response{
			Code: http.StatusOK,
			Msg:  "成功",
			Data: s,
		}, nil
	}
	return nil, nil
}
